<template>
  <div class="wechat-login">
    <a-button 
      type="primary" 
      size="large" 
      class="wechat-btn"
      @click="showQRCode"
      :loading="loading"
      block
    >
      <template #icon>
        <svg class="w-5 h-5" viewBox="0 0 24 24" fill="currentColor">
          <path d="M8.691 2.188C3.891 2.188 0 5.476 0 9.53c0 2.212 1.17 4.203 3.002 5.55a.59.59 0 0 1 .213.665l-.39 1.48c-.019.07-.048.141-.048.213 0 .163.13.295.29.295a.326.326 0 0 0 .167-.054l1.903-1.114a.864.864 0 0 1 .717-.098 10.16 10.16 0 0 0 2.837.403c.276 0 .543-.027.811-.05-.857-2.578.157-4.972 1.932-6.446 1.703-1.415 4.882-1.900 7.60.5.5-3.187-2.75-6.874-8.343-6.874zm-3.375 7.25a.5.5 0 1 1-.001-1.001.5.5 0 0 1 .001 1.001zm4.75 0a.5.5 0 1 1-.001-1.001.5.5 0 0 1 .001 1.001z"/>
          <path d="M16.188 9.375c-3.344 0-6.094 2.313-6.094 5.156 0 1.688.906 3.203 2.344 4.219a.468.468 0 0 1 .156.531l-.312 1.125c-.016.055-.031.109-.031.164 0 .125.094.227.219.227a.28.28 0 0 0 .125-.039l1.453-.852a.702.702 0 0 1 .547-.078c.5.125 1.031.195 1.594.195 3.344 0 6.094-2.313 6.094-5.156s-2.75-5.156-6.094-5.156zm-2.344 4.375a.375.375 0 1 1 0-.75.375.375 0 0 1 0 .75zm3.5 0a.375.375 0 1 1 0-.75.375.375 0 0 1 0 .75z"/>
        </svg>
      </template>
      微信登录
    </a-button>
    
    <a-modal
      v-model:open="qrModalVisible"
      title="微信扫码登录"
      :footer="null"
      :maskClosable="false"
      :width="400"
      centered
      @cancel="handleModalClose"
    >
      <div class="qr-container">
        <div v-if="qrCodeUrl" class="qr-code">
          <qrcode-vue :value="qrCodeUrl" :size="200" level="M" />
        </div>
        <div v-else class="qr-loading">
          <a-spin size="large" tip="正在生成二维码..." />
        </div>
        
        <div class="qr-tips">
          <p class="text-center text-gray-600 mb-2">请使用微信扫描二维码</p>
          <p class="text-center text-gray-500 text-sm">
            <template v-if="authStatus === 'waiting'">
              扫码后点击"确认登录"
            </template>
            <template v-else-if="authStatus === 'scanned'">
              请在手机上确认登录
            </template>
          </p>
          <p v-if="countdown > 0 && authStatus !== 'expired'" class="text-center text-gray-400 text-xs mt-2">
            二维码将在 {{ Math.floor(countdown / 60) }}:{{ String(countdown % 60).padStart(2, '0') }} 后过期
          </p>
        </div>
        
        <div class="qr-status">
          <div v-if="authStatus === 'waiting'" class="status-waiting">
            <a-spin size="small" />
            <span class="ml-2">等待扫码...</span>
          </div>
          <div v-else-if="authStatus === 'scanned'" class="status-scanned">
            <check-circle-outlined class="text-green-500" />
            <span class="ml-2 text-green-600">扫码成功，请在手机上确认</span>
          </div>
          <div v-else-if="authStatus === 'expired'" class="status-expired">
            <exclamation-circle-outlined class="text-orange-500" />
            <span class="ml-2 text-orange-600">二维码已过期</span>
            <a-button type="link" @click="refreshQRCode" class="ml-2">刷新</a-button>
          </div>
          <div v-else-if="authStatus === 'error'" class="status-error">
            <close-circle-outlined class="text-red-500" />
            <span class="ml-2 text-red-600">{{ errorMessage || '登录失败' }}</span>
            <a-button type="link" @click="refreshQRCode" class="ml-2">重试</a-button>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onUnmounted } from 'vue'
import { message } from 'ant-design-vue'
import { CheckCircleOutlined, ExclamationCircleOutlined, CloseCircleOutlined } from '@ant-design/icons-vue'
import QrcodeVue from 'qrcode.vue'
import { getWeChatLoginUrl, wechatLogin, checkWeChatLoginStatus } from '@/api/auth'

// Props
interface Props {
  // 可以添加一些配置属性
}

const props = withDefaults(defineProps<Props>(), {})

// Emits
interface Emits {
  (e: 'success', data: any): void
  (e: 'error', error: any): void
}

const emit = defineEmits<Emits>()

// Reactive data
const loading = ref(false)
const qrModalVisible = ref(false)
const qrCodeUrl = ref('')
const authStatus = ref<'waiting' | 'scanned' | 'expired' | 'error'>('waiting')
const errorMessage = ref('')
const stateParam = ref('')
const retryCount = ref(0)
const maxRetries = 3
const countdown = ref(0)

// Timers
let pollTimer: NodeJS.Timeout | null = null
let expireTimer: NodeJS.Timeout | null = null
let countdownTimer: NodeJS.Timeout | null = null

// Methods
const showQRCode = async () => {
  loading.value = true
  try {
    const response = await getWeChatLoginUrl()
    
    if (response.code === 200 || response.success) {
      const { loginUrl, state, expiresIn } = response.data
      qrCodeUrl.value = loginUrl
      stateParam.value = state
      qrModalVisible.value = true
      authStatus.value = 'waiting'
      
      // 开始轮询状态
      startPolling()
      
      // 设置过期定时器和倒计时 (默认5分钟过期)
      const expireTime = expiresIn || 300
      countdown.value = expireTime
      
      // 倒计时定时器
      countdownTimer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(countdownTimer!)
          countdownTimer = null
        }
      }, 1000)
      
      // 过期定时器
      expireTimer = setTimeout(() => {
        if (authStatus.value === 'waiting' || authStatus.value === 'scanned') {
          authStatus.value = 'expired'
          stopPolling()
        }
      }, expireTime * 1000)
    } else {
      message.error(response.message || '获取微信登录URL失败')
    }
  } catch (error: any) {
    message.error(error.message || '获取微信登录URL失败')
  } finally {
    loading.value = false
  }
}

const refreshQRCode = async () => {
  stopPolling()
  clearExpireTimer()
  authStatus.value = 'waiting'
  errorMessage.value = ''
  retryCount.value = 0
  countdown.value = 0
  qrCodeUrl.value = ''
  await showQRCode()
}

const startPolling = () => {
  // 立即检查一次状态
  checkAuthStatus()
  
  // 开始定时轮询，每2秒检查一次状态
  pollTimer = setInterval(() => {
    if (authStatus.value === 'waiting' || authStatus.value === 'scanned') {
      checkAuthStatus()
    } else {
      // 如果状态不是等待中，停止轮询
      stopPolling()
    }
  }, 2000)
}

const stopPolling = () => {
  if (pollTimer) {
    clearInterval(pollTimer)
    pollTimer = null
  }
}

const clearExpireTimer = () => {
  if (expireTimer) {
    clearTimeout(expireTimer)
    expireTimer = null
  }
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
}

const checkAuthStatus = async () => {
  try {
    if (!stateParam.value) {
      return
    }
    
    const response = await checkWeChatLoginStatus(stateParam.value)
    
    if (response.code === 200 || response.success) {
      const { status, data } = response.data
      
      switch (status) {
        case 'waiting':
          // 继续等待
          break
        case 'scanned':
          authStatus.value = 'scanned'
          break
        case 'confirmed':
          // 用户在微信中确认登录
          authStatus.value = 'scanned'
          // 尝试完成登录
          await completeLogin(data)
          break
        case 'expired':
          authStatus.value = 'expired'
          stopPolling()
          break
        case 'cancelled':
          authStatus.value = 'error'
          errorMessage.value = '用户取消登录'
          stopPolling()
          break
        default:
          break
      }
    }
  } catch (error: any) {
    // 轮询过程中的错误处理
    retryCount.value++
    console.warn('WeChat auth status check failed:', error)
    
    // 如果重试次数超过限制，停止轮询并显示错误
    if (retryCount.value >= maxRetries) {
      authStatus.value = 'error'
      errorMessage.value = '网络连接异常，请刷新重试'
      stopPolling()
    }
  }
}

const completeLogin = async (authData: any) => {
  try {
    if (authData && authData.code && authData.state) {
      const response = await wechatLogin(authData.code, authData.state)
      
      if (response.code === 200 || response.success) {
        handleAuthSuccess(response.data)
      } else {
        handleAuthError({ message: response.message || '登录失败' })
      }
    }
  } catch (error: any) {
    handleAuthError(error)
  }
}

const handleAuthSuccess = (data: any) => {
  authStatus.value = 'scanned'
  stopPolling()
  clearExpireTimer()
  
  setTimeout(() => {
    qrModalVisible.value = false
    emit('success', data)
    message.success('微信登录成功')
  }, 1000)
}

const handleAuthError = (error: any) => {
  authStatus.value = 'error'
  errorMessage.value = error.message || '登录失败'
  stopPolling()
  clearExpireTimer()
  emit('error', error)
}

// 监听来自父窗口的消息（用于处理微信回调）
const handleMessage = (event: MessageEvent) => {
  if (event.origin !== window.location.origin) {
    return
  }
  
  const { type, data } = event.data
  
  if (type === 'WECHAT_AUTH_SUCCESS') {
    handleAuthSuccess(data)
  } else if (type === 'WECHAT_AUTH_ERROR') {
    handleAuthError(data)
  }
}

const handleModalClose = () => {
  stopPolling()
  clearExpireTimer()
  qrModalVisible.value = false
  authStatus.value = 'waiting'
  errorMessage.value = ''
  qrCodeUrl.value = ''
  stateParam.value = ''
  retryCount.value = 0
  countdown.value = 0
}

// 生命周期
onUnmounted(() => {
  stopPolling()
  clearExpireTimer()
  window.removeEventListener('message', handleMessage)
})

// 添加消息监听器
window.addEventListener('message', handleMessage)

// 暴露方法给父组件
defineExpose({
  showQRCode,
  refreshQRCode
})
</script>

<style scoped>
.wechat-login {
  width: 100%;
}

.wechat-btn {
  background: #07c160;
  border-color: #07c160;
  height: 48px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
}

.wechat-btn:hover,
.wechat-btn:focus {
  background: #06ad56;
  border-color: #06ad56;
}

.qr-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.qr-code {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.qr-loading {
  height: 240px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
}

.qr-tips {
  margin-bottom: 20px;
  text-align: center;
}

.qr-status {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 32px;
}

.status-waiting,
.status-scanned,
.status-expired,
.status-error {
  display: flex;
  align-items: center;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .qr-code {
    padding: 10px;
  }
  
  .qr-container {
    padding: 10px 0;
  }
}
</style>